package com.hzit.sb2.util.weixin;

import com.alibaba.fastjson.JSONObject;
import com.hzit.sb2.redis.RedisUtil;
import com.hzit.sb2.util.MyConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AccessTokenUtil {
    final static String APPID = "wx8fd6bd444fe72900";
    final static String SECRET = "d5c4bb2803b7633ddd22041e8857e73e";

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    HttpClientUtil httpClientUtil;

    public String getAccessToken(){
        //从redis中获取token
        Object obj = redisUtil.get(MyConst.WEIXIN_TOKEN);
        if(obj != null){//redis存在token则直接返回
            return (String)obj;
        }
        //redis中不存在,远程调用微信API获取token
        String token = remoteWXToken();
        redisUtil.set(MyConst.WEIXIN_TOKEN,token,6000l);
        return token;
    }

    private String remoteWXToken() {
        System.out.println("--------------------->远程调用微信API获取token<-------------------------");
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECRET;
        String entity = httpClientUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(entity);
        //正常：{"access_token":"ACCESS_TOKEN","expires_in":7200}
        //异常: {"errcode":40013,"errmsg":"invalid appid"}
        if(jsonObject.containsKey("access_token")){
            return jsonObject.getString("access_token");
        }
        System.err.println("获取token失败："+entity);
        return null;
    }
}
